package com.validator;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckUsername extends FieldValidatorSupport {
	private boolean trim = true;

	@Override
	public void validate(Object o) throws ValidationException {
		//1. 获取字段的名字和值
		String fieldName = getFieldName();
		String fieldValue = (String) getFieldValue(fieldName, o);
		//2. 验证
		if (fieldValue == null)
			return;
		if (trim)
			fieldValue = fieldValue.trim();
		if (fieldValue.length() == 0) {
			return;
		}
		String reg = "^[a-zA-Z0-9_-]{4,16}$";
		//编译正则表达式
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(fieldValue);
		// 字符串是否与正则表达式相匹配
		boolean rs = matcher.matches();
		if (rs == false) {
			addFieldError(fieldName, o);
		}

	}

}
